import tkinter as tk
import tkinter.font as tkFont
import tkinter.filedialog as tkFileDialog
import tkinter.messagebox as tkMessageBox

import os

class App:
    DEFAULT_LOCAL_REGION_PATH       = "result_local_region_file_name"
    DEFAULT_TRADE_LINE_PATH         = "result_trade_line_file_name"
    DEFAULT_SALES_REGION_IB_PATH    = "result_sales_region_ib_file_name"
    DEFAULT_SALES_REGION_OB_PATH    = "result_sales_region_ob_file_name"
    DEFAULT_SALES_COUNTRY_IB_PATH   = "result_sales_country_ib_file_name"
    DEFAULT_SALES_COUNTRY_OB_PATH   = "result_sales_country_ob_file_name"

    def gui_reset(self):
        self.le_source_1_path.set("source/2024 wk10 1711.csv")
        self.le_source_2_path.set("source/2024 wk10 1713.csv")

        self.le_year_source_1.set("Year")
        self.le_week_source_1.set("Week")
        self.le_year_source_2.set("Year")
        self.le_week_source_2.set("Week")

        self.le_result_dir.set("./result")

        self.le_local_region_path.set(App.DEFAULT_LOCAL_REGION_PATH)
        self.le_trade_line_path.set(App.DEFAULT_TRADE_LINE_PATH)
        self.le_sales_region_ib_path.set(App.DEFAULT_SALES_REGION_IB_PATH)
        self.le_sales_region_ob_path.set(App.DEFAULT_SALES_REGION_OB_PATH)
        self.le_sales_country_ib_path.set(App.DEFAULT_SALES_COUNTRY_IB_PATH)
        self.le_sales_country_ob_path.set(App.DEFAULT_SALES_COUNTRY_OB_PATH)

        #parse source 1 and 2
        self.set_year_week(self.le_source_1_path.get(), self.le_year_source_1, self.le_week_source_1)
        self.set_year_week(self.le_source_2_path.get(), self.le_year_source_2, self.le_week_source_2)
        # changed from year, week
        self.set_result_file_path()



    def __init__(self, root):
        root.title("China Shipping Tool")
        width=570
        height=480
        screenwidth = root.winfo_screenwidth()
        screenheight = root.winfo_screenheight()
        alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
        root.geometry(alignstr)
        root.resizable(width=False, height=False)



        # lbl_source_1 le_source_1_path  btn_source_1 le_year_source_1  le_week_source_1

        lbl_source_1=tk.Label(root)
        ft = tkFont.Font(family='Times',size=10)
        lbl_source_1["font"] = ft
        lbl_source_1["fg"] = "#333333"
        lbl_source_1["justify"] = "center"
        lbl_source_1["text"] = "Source 11:"
        lbl_source_1.place(x=10,y=10,width=70,height=30)

        self.le_source_1_path = tk.StringVar()
        le_source_1_path=tk.Entry(root)
        le_source_1_path["borderwidth"] = "1px"
        ft = tkFont.Font(family='Times',size=10)
        le_source_1_path["font"] = ft
        le_source_1_path["fg"] = "#333333"
        le_source_1_path["justify"] = "center"
        le_source_1_path.place(x=80,y=10,width=380,height=30)
        le_source_1_path["textvariable"] = self.le_source_1_path

        btn_source_1=tk.Button(root)
        btn_source_1["bg"] = "#efefef"
        ft = tkFont.Font(family='Times',size=10)
        btn_source_1["font"] = ft
        btn_source_1["fg"] = "#000000"
        btn_source_1["justify"] = "center"
        btn_source_1["text"] = "..."
        btn_source_1.place(x=460,y=10,width=30,height=30)
        btn_source_1["command"] = self.btn_source_1_command


        self.le_year_source_1 = tk.StringVar()
        le_year_source_1=tk.Entry(root)
        ft = tkFont.Font(family='Times',size=10)
        le_year_source_1["font"] = ft
        le_year_source_1["fg"] = "#333333"
        le_year_source_1["justify"] = "center"
        le_year_source_1.place(x=495,y=10,width=35,height=30)
        le_year_source_1["textvariable"] = self.le_year_source_1
        le_year_source_1.bind("<KeyRelease>", self.le_year_week_source_1_text_changed)
        self.le_year_source_1_obj = le_year_source_1


        self.le_week_source_1 = tk.StringVar()
        le_week_source_1=tk.Entry(root)
        ft = tkFont.Font(family='Times',size=10)
        le_week_source_1["font"] = ft
        le_week_source_1["fg"] = "#333333"
        le_week_source_1["justify"] = "center"
        le_week_source_1.place(x=535,y=10,width=30,height=30)
        le_week_source_1["textvariable"] = self.le_week_source_1
        le_week_source_1.bind("<KeyRelease>", self.le_year_week_source_1_text_changed)
        self.le_week_source_1_obj = le_week_source_1

        ####################  Local Region &  Trade Line ################

        GLabel_736=tk.Label(root)
        ft = tkFont.Font(family='Times',size=10)
        GLabel_736["font"] = ft
        GLabel_736["fg"] = "#333333"
        GLabel_736["justify"] = "left"
        GLabel_736["text"] = "Local Region Result :"
        GLabel_736.place(x=10,y=50,width=130,height=30)

        self.le_local_region_path = tk.StringVar()
        le_local_region_path=tk.Entry(root, state="readonly")
        le_local_region_path["borderwidth"] = "1px"
        ft = tkFont.Font(family='Times',size=10)
        le_local_region_path["font"] = ft
        le_local_region_path["fg"] = "#333333"
        le_local_region_path["justify"] = "center"
        le_local_region_path.place(x=150,y=50,width=400,height=30)
        le_local_region_path["textvariable"] = self.le_local_region_path

        GLabel_169=tk.Label(root)
        ft = tkFont.Font(family='Times',size=10)
        GLabel_169["font"] = ft
        GLabel_169["fg"] = "#333333"
        GLabel_169["justify"] = "left"
        GLabel_169["text"] = "Trade Line Result :"
        GLabel_169.place(x=10,y=90,width=130,height=30)

        self.le_trade_line_path = tk.StringVar()
        le_trade_line_path=tk.Entry(root, state="readonly")
        le_trade_line_path["borderwidth"] = "1px"
        ft = tkFont.Font(family='Times',size=10)
        le_trade_line_path["font"] = ft
        le_trade_line_path["fg"] = "#333333"
        le_trade_line_path["justify"] = "center"
        le_trade_line_path.place(x=150,y=90,width=400,height=30)
        le_trade_line_path["textvariable"] = self.le_trade_line_path
        

        # lbl_source_2 le_source_2_path btn_source_2 le_year_source_2  le_week_source_2

        lbl_source_2=tk.Label(root)
        ft = tkFont.Font(family='Times',size=10)
        lbl_source_2["font"] = ft
        lbl_source_2["fg"] = "#333333"
        lbl_source_2["justify"] = "center"
        lbl_source_2["text"] = "Source 13:"
        lbl_source_2.place(x=10,y=150,width=70,height=30)

        self.le_source_2_path = tk.StringVar()
        le_source_2_path=tk.Entry(root)
        le_source_2_path["borderwidth"] = "1px"
        ft = tkFont.Font(family='Times',size=10)
        le_source_2_path["font"] = ft
        le_source_2_path["fg"] = "#333333"
        le_source_2_path["justify"] = "center"
        le_source_2_path.place(x=80,y=150,width=380,height=30)
        le_source_2_path["textvariable"] = self.le_source_2_path

        btn_source_2=tk.Button(root)
        btn_source_2["bg"] = "#efefef"
        ft = tkFont.Font(family='Times',size=10)
        btn_source_2["font"] = ft
        btn_source_2["fg"] = "#000000"
        btn_source_2["justify"] = "center"
        btn_source_2["text"] = "..."
        btn_source_2.place(x=460,y=150,width=30,height=30)
        btn_source_2["command"] = self.btn_source_2_command

        self.le_year_source_2 = tk.StringVar()
        le_year_source_2=tk.Entry(root)
        ft = tkFont.Font(family='Times',size=10)
        le_year_source_2["font"] = ft
        le_year_source_2["fg"] = "#333333"
        le_year_source_2["justify"] = "center"
        le_year_source_2.place(x=495,y=150,width=35,height=30)
        le_year_source_2["textvariable"] = self.le_year_source_2
        le_year_source_2.bind("<KeyRelease>", self.le_year_week_source_2_text_changed)
        self.le_year_source_2_obj = le_year_source_2

        self.le_week_source_2 = tk.StringVar()
        le_week_source_2=tk.Entry(root)
        ft = tkFont.Font(family='Times',size=10)
        le_week_source_2["font"] = ft
        le_week_source_2["fg"] = "#333333"
        le_week_source_2["justify"] = "center"
        le_week_source_2.place(x=535,y=150,width=30,height=30)
        le_week_source_2["textvariable"] = self.le_week_source_2
        le_week_source_2.bind("<KeyRelease>", self.le_year_week_source_2_text_changed)
        self.le_week_source_2_obj  = le_week_source_2


        ####################  Sales Region & Country  ################

        GLabel_387=tk.Label(root)
        ft = tkFont.Font(family='Times',size=10)
        GLabel_387["font"] = ft
        GLabel_387["fg"] = "#333333"
        GLabel_387["justify"] = "left"
        GLabel_387["text"] = "Sales Region IB :"
        GLabel_387.place(x=10,y=190,width=130,height=30)

        self.le_sales_region_ib_path = tk.StringVar()
        le_sales_region_ib_path=tk.Entry(root, state="readonly")
        le_sales_region_ib_path["borderwidth"] = "1px"
        ft = tkFont.Font(family='Times',size=10)
        le_sales_region_ib_path["font"] = ft
        le_sales_region_ib_path["fg"] = "#333333"
        le_sales_region_ib_path["justify"] = "center"
        le_sales_region_ib_path.place(x=150,y=190,width=400,height=30)
        le_sales_region_ib_path["textvariable"] = self.le_sales_region_ib_path

        GLabel_555=tk.Label(root)
        ft = tkFont.Font(family='Times',size=10)
        GLabel_555["font"] = ft
        GLabel_555["fg"] = "#333333"
        GLabel_555["justify"] = "left"
        GLabel_555["text"] = "Sales Region OB :"
        GLabel_555.place(x=10,y=230,width=130,height=30)

        self.le_sales_region_ob_path = tk.StringVar()
        le_sales_region_ob_path=tk.Entry(root, state="readonly")
        le_sales_region_ob_path["borderwidth"] = "1px"
        ft = tkFont.Font(family='Times',size=10)
        le_sales_region_ob_path["font"] = ft
        le_sales_region_ob_path["fg"] = "#333333"
        le_sales_region_ob_path["justify"] = "center"
        le_sales_region_ob_path.place(x=150,y=230,width=400,height=30)
        le_sales_region_ob_path["textvariable"] = self.le_sales_region_ob_path

        GLabel_147=tk.Label(root)
        ft = tkFont.Font(family='Times',size=10)
        GLabel_147["font"] = ft
        GLabel_147["fg"] = "#333333"
        GLabel_147["justify"] = "left"
        GLabel_147["text"] = "Sales Country IB  :"
        GLabel_147.place(x=10,y=270,width=130,height=30)

        self.le_sales_country_ib_path = tk.StringVar() 
        le_sales_country_ib_path=tk.Entry(root, state="readonly")
        le_sales_country_ib_path["borderwidth"] = "1px"
        ft = tkFont.Font(family='Times',size=10)
        le_sales_country_ib_path["font"] = ft
        le_sales_country_ib_path["fg"] = "#333333"
        le_sales_country_ib_path["justify"] = "center"
        le_sales_country_ib_path.place(x=150,y=270,width=400,height=30)
        le_sales_country_ib_path["textvariable"] = self.le_sales_country_ib_path

        GLabel_75=tk.Label(root)
        ft = tkFont.Font(family='Times',size=10)
        GLabel_75["font"] = ft
        GLabel_75["fg"] = "#333333"
        GLabel_75["justify"] = "left"
        GLabel_75["text"] = "Sales Country OB :"
        GLabel_75.place(x=10,y=310,width=130,height=30)

        self.le_sales_country_ob_path = tk.StringVar()
        le_sales_country_ob_path=tk.Entry(root, state="readonly")
        le_sales_country_ob_path["borderwidth"] = "1px"
        ft = tkFont.Font(family='Times',size=10)
        le_sales_country_ob_path["font"] = ft
        le_sales_country_ob_path["fg"] = "#333333"
        le_sales_country_ob_path["justify"] = "center"
        le_sales_country_ob_path.place(x=150,y=310,width=400,height=30)
        le_sales_country_ob_path["textvariable"] = self.le_sales_country_ob_path


        ############# Result Directory #################### 

        GLabel_94=tk.Label(root)
        ft = tkFont.Font(family='Times',size=10)
        GLabel_94["font"] = ft
        GLabel_94["fg"] = "#333333"
        GLabel_94["justify"] = "center"
        GLabel_94["text"] = "Result  path :"
        GLabel_94.place(x=10,y=370,width=70,height=25)

        self.le_result_dir = tk.StringVar()
        le_result_dir=tk.Entry(root)
        le_result_dir["borderwidth"] = "1px"
        ft = tkFont.Font(family='Times',size=10)
        le_result_dir["font"] = ft
        le_result_dir["fg"] = "#333333"
        le_result_dir["justify"] = "center"
        le_result_dir.place(x=80,y=370,width=380,height=30)
        le_result_dir["textvariable"] = self.le_result_dir

        btn_result_dir=tk.Button(root)
        btn_result_dir["bg"] = "#efefef"
        ft = tkFont.Font(family='Times',size=10)
        btn_result_dir["font"] = ft
        btn_result_dir["fg"] = "#000000"
        btn_result_dir["justify"] = "center"
        btn_result_dir["text"] = "..."
        btn_result_dir.place(x=460,y=370,width=30,height=30)
        btn_result_dir["command"] = self.btn_result_dir_command

        ########################   Confirm  & Reset ###################

        btn_confirm=tk.Button(root)
        btn_confirm["bg"] = "#efefef"
        ft = tkFont.Font(family='Times',size=10)
        btn_confirm["font"] = ft
        btn_confirm["fg"] = "#000000"
        btn_confirm["justify"] = "center"
        btn_confirm["text"] = "Confirm"
        btn_confirm.place(x=100,y=420,width=160,height=30)
        btn_confirm["command"] = self.btn_confirm_command

        btn_reset=tk.Button(root)
        btn_reset["bg"] = "#efefef"
        ft = tkFont.Font(family='Times',size=10)
        btn_reset["font"] = ft
        btn_reset["fg"] = "#000000"
        btn_reset["justify"] = "center"
        btn_reset["text"] = "Reset"
        btn_reset.place(x=340,y=420,width=160,height=30)
        btn_reset["command"] = self.btn_reset_command

        self.gui_reset()


    @staticmethod
    def get_year(year):
        if year.isdigit():
            if int(year) > 1000 and int(year) < 3000:
                return (True, year)
        return (False, "Year")
    @staticmethod
    def get_week(week):
        week = week.strip()
        if week.isdigit(): 
            i_week = int(week)
            if i_week > 0 and i_week < 54:
                return (True, week)
        return (False, "Week")



    def parse_file_name_to_year_week(self, source_name):
        file_name = os.path.basename(source_name)
        if len(file_name) >= 14:
            ok, year = App.get_year(file_name[0:4])
            if ok:
                ok, week = App.get_week(file_name[7:9])
                if ok:
                    return (True, year, week)
                else:
                    return (True, year, "Week")
            else:
                return (False, "Year", "Week")
        #end if
        return (False, "Year", "Week")

    def set_year_week(self, source_path, strval_year, strval_week):
        ok, year, week = self.parse_file_name_to_year_week(source_path)
        #if not ok:
            #tkMessageBox.showwarning(title="Error Year or Week from File Name ", message="please select other source file, or input year or week manually!")
        strval_year.set(year)
        strval_week.set(week)
        








    def btn_source_1_command(self):
        source_path_obj = tkFileDialog.askopenfile()
        if source_path_obj is not None:
            self.le_source_1_path.set(source_path_obj.name)
            self.set_year_week(source_path_obj.name, self.le_year_source_1, self.le_week_source_1)
            self.set_result_file_path()
        else:
            print("logger: please select one file") #TODO: 

    def btn_source_2_command(self):
        source_path_obj = tkFileDialog.askopenfile()
        if source_path_obj is not None:
            self.le_source_2_path.set(source_path_obj.name)
            self.set_year_week(source_path_obj.name, self.le_year_source_2, self.le_week_source_2)
            self.set_result_file_path()
        else:
            print("logger: please select one file") #TODO:

    def set_result_local_trade_path(self):
        ok, year = App.get_year(self.le_year_source_1.get())
        if ok:
            ok, week = App.get_week(self.le_week_source_1.get())
            if ok:
                self.le_local_region_path.set("result_local_region_week_%s%02d.csv" %(year, int(week)))
                self.le_trade_line_path.set("result_trade_line_week_%s%02d.csv" % (year, int(week)))
            else:
                self.le_trade_line_path.set(App.DEFAULT_TRADE_LINE_PATH)
                self.le_trade_line_path.set(App.DEFAULT_TRADE_LINE_PATH)
        else:
            self.le_local_region_path.set(App.DEFAULT_LOCAL_REGION_PATH)
            self.le_trade_line_path.set(App.DEFAULT_TRADE_LINE_PATH)
        
    def set_result_sales_path(self):
        ok,year = App.get_year(self.le_year_source_2.get())
        if ok:
            ok,week = App.get_week(self.le_week_source_2.get())
            if ok:
                self.le_sales_region_ib_path.set("result_sales_region_week_ib_%s%02d.csv" %(year, int(week)))
                self.le_sales_region_ob_path.set("result_sales_region_week_ob_%s%02d.csv" %(year, int(week)))
                self.le_sales_country_ib_path.set("result_sales_country_week_ib_%s%02d.csv" %(year, int(week)))
                self.le_sales_country_ob_path.set("result_sales_country_week_ob_%s%02d.csv" %(year, int(week)))
            else:
                self.le_sales_region_ib_path.set(App.DEFAULT_SALES_REGION_IB_PATH)
                self.le_sales_region_ob_path.set(App.DEFAULT_SALES_REGION_OB_PATH)
                self.le_sales_country_ib_path.set(App.DEFAULT_SALES_COUNTRY_IB_PATH)
                self.le_sales_country_ob_path.set(App.DEFAULT_SALES_COUNTRY_OB_PATH)
        else:
            self.le_sales_region_ib_path.set(App.DEFAULT_SALES_REGION_IB_PATH)
            self.le_sales_region_ob_path.set(App.DEFAULT_SALES_REGION_OB_PATH)
            self.le_sales_country_ib_path.set(App.DEFAULT_SALES_COUNTRY_IB_PATH)
            self.le_sales_country_ob_path.set(App.DEFAULT_SALES_COUNTRY_OB_PATH)
        
    def set_result_file_path(self):
        self.set_result_local_trade_path()
        self.set_result_sales_path()

        
    def btn_result_dir_command(self):
        result_dir = tkFileDialog.askdirectory(mustexist=True)
        if result_dir is not None:
            self.le_result_dir.set(result_dir)
            
            self.set_result_file_path()
        else:
            print("logger: please select one directory") #TODO:

    def btn_reset_command(self):
        self.gui_reset()

    # check the entry of year, week is valid
    def check_year_week_source(self, year_str, week_str):
        ok, _ = App.get_year(year_str)
        if not ok:  
            return (False, 1)
        ok, _ = App.get_week(week_str)
        if not ok: 
            return (False, 2)
        return (True, 0)

    # check the year == year, week == week
    def check_year_week_equal(self):
        return self.le_year_source_1.get() == self.le_year_source_2.get() and self.le_week_source_1.get() == self.le_week_source_2.get()

    def le_year_week_source_1_text_changed(self, event):
        ok, _ = self.check_year_week_source(self.le_year_source_1.get(), self.le_week_source_1.get())
        if ok:
            self.set_result_local_trade_path()

    def le_year_week_source_2_text_changed(self, event):
        ok, _ = self.check_year_week_source(self.le_year_source_2.get(), self.le_week_source_2.get())
        if ok:
            self.set_result_sales_path()


    def btn_confirm_command(self):
        ok, y_w = self.check_year_week_source(self.le_year_source_1.get(), self.le_week_source_1.get())
        if ok:
            self.set_result_local_trade_path()
        else:
            tkMessageBox.showerror(title="Year Week invalid", message="Local Region & Trade Line 's Year/Week value error!")
            if y_w == 1:
                self.le_year_source_1_obj.select_range(0, tk.END)
                self.le_year_source_1_obj.focus_set()
            else:
                self.le_week_source_1_obj.select_range(0, tk.END)
                self.le_week_source_1_obj.focus_set()
            return None

        ok, y_w = self.check_year_week_source(self.le_year_source_2.get(), self.le_week_source_2.get())
        if ok:
            self.set_result_sales_path()
        else:
            tkMessageBox.showerror(title="Year Week invalid", message="Sales Year/Week value error!")
            if y_w == 1:
                self.le_year_source_2_obj.select_range(0, tk.END)
                self.le_year_source_2_obj.focus_set()
            else:
                self.le_week_source_2_obj.select_range(0, tk.END)
                self.le_week_source_2_obj.focus_set()

            return None

        if not self.check_year_week_equal():
            tkMessageBox.showerror(title="Year Week invalid", message="Local-[Year/Week] not equal to Sales-[Year/Week]")    
            return None

        year = int(self.le_year_source_1.get())
        week = int(self.le_week_source_1.get())
        source_11_name = self.le_source_1_path.get()
        source_13_name = self.le_source_2_path.get()
        result_dir = self.le_result_dir.get()

        from biz_inter import Biz
        Biz.create(year, week, source_11_name, source_13_name, result_dir).run()
        tkMessageBox.showinfo(title="work finished", message="running ok")

if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.mainloop()

